<?php


namespace app\beautiful\controller\admin\finance;


use app\BaseController;

use app\beautiful\model\finance\AccountBalanceModel;
use app\beautiful\model\finance\SettlementModel;
use app\beautiful\model\finance\SettleOrderModel;
use app\beautiful\model\finance\WithdrawAccountModel;
use app\beautiful\model\finance\WithdrawModel;
use app\beautiful\model\LevelModel;
use app\beautiful\model\order\GoodsOrderItemModel;
use app\beautiful\model\order\GoodsOrderModel;
use app\beautiful\model\order\OrderGoodsModel;
use app\common\logic\DataLogic;
use app\common\model\ShopBalanceLogsModel;
use app\common\model\ShopDetailModel;
use app\stores\model\order\BuyOrderModel;
use think\facade\Db;
use function EasyWeChat\Kernel\Support\str_random;

class Settlement extends BaseController
{
    /*账户信息*/
    public function account(){
        if(null === $account = AccountBalanceModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0])->find()){
            $account = new AccountBalanceModel();
            $account->shop_id = $this->request->shopId;
            $account->account_money = sprintf("%.2f",0);
            $account->spare_money = sprintf("%.2f",0);
            $account->save();
        }
        $shop_detail = ShopDetailModel::where(['shop_id'=>$this->request->shopId])->find();
        //提现账户
        $withdraw_account = WithdrawAccountModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0])->order(['is_default' => 'desc'])->find();
        $account['account_number'] = $withdraw_account===null?'暂未绑定':$withdraw_account->account_number;
        $account['open_bank_name'] = $withdraw_account===null?'暂未绑定':$withdraw_account->open_bank_name;
        $account['type'] = $withdraw_account===null?'暂未绑定':$withdraw_account->type;
        $account['shop_name'] = $this->request->shop->name;
        $account['wx_face'] = $shop_detail->logo;
        //提现笔数
        $account['withdraw_count'] = WithdrawModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'status'=>1])->count();
        //结算笔数
        $account['settlement_count'] = SettlementModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0])->count();

       return $this->success($account);
   }
    /*结算账单列表*/
    public function index()

    {
        $year = $this->request->param('year/d',date('Y'));
        $month = $this->request->param('month/d',date('m'));

        $where = [

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

        ];
        $start_time =mktime(0,0,0,$month,1,$year);

        $end_time = mktime(23,59,59,($month+1),0,$year);

        $settlement = new SettlementModel();

        $settlement = $settlement->whereBetweenTime('add_time',$start_time,$end_time);

        $order = ['add_time'=>'desc'];

        $field = "settlement_id,settlement_price,add_time";

        $append = [];

        $return = DataLogic::getDataList($settlement,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        //提现笔数
        $withdraw = WithdrawModel::whereBetweenTime('add_time',$start_time,$end_time)->where(['shop_id'=>$this->request->shopId,'status'=>1,'is_delete'=>0])->field('count(*) as total_withdraw_num,sum(before_money-after_money) as total_withdraw_money')->select()->toArray();
        $return['total_withdraw_num'] = $withdraw[0]['total_withdraw_num'];
        $return['total_withdraw_money'] = $withdraw[0]['total_withdraw_money'];
        //结算笔数
        $return['total_settlement_num'] = $return['total'];
        $return['total_settlement_money'] = $settlement->where($where)->sum('settlement_price');
        //结算金额

        return $this->success($return);

    }
    /*结算明细*/
    public function detail(){
        $settlement_id = $this->request->param('settlement_id/d',0);
        if(null === $settlement = SettlementModel::where(['shop_id'=>$this->request->shopId,'settlement_id'=>$settlement_id,'is_delete'=>0])->json(['order_count_detail','pay_detail','deduct_detail','coupon_detail','write_off_detail'],true)->find()){
            return $this->error('结算不存在');
        }
        $settlement['deduct_detail'] = [
            'bonus_price'=>sprintf("%.2f", $settlement['deduct_detail']['bonus_price']),
            'consume_price'=>sprintf("%.2f", $settlement['deduct_detail']['consume_price']),
            'lock_price'=>sprintf("%.2f", $settlement['deduct_detail']['lock_price']),
            'other_price'=>sprintf("%.2f", $settlement['deduct_detail']['other_price']),
            'promotion_price'=>sprintf("%.2f", $settlement['deduct_detail']['promotion_price']),
            'service_price'=>sprintf("%.2f", $settlement['deduct_detail']['service_price']),
        ];
        $tj = refundTj($settlement,$this->request->shopId);

        $settlement['settlement_time'] .=' 00:00:00-23:59:59';

        $pay_detail = $settlement['pay_detail'];
        if($pay_detail)   $pay_detail['refund_money'] = $tj['refund_money'];

        $order_count_detail = $settlement['order_count_detail'];
        if($order_count_detail)   $order_count_detail['all_refund_count'] = $tj['all_refund_count'];
        if($order_count_detail)   $order_count_detail['bf_refund_count'] = $tj['bf_refund_count'];

        $settlement['order_count'] = $settlement['order_count'] + $tj['all_refund_count'];
        if($pay_detail) $pay_detail['platform_money'] = sprintf("%.2f",$pay_detail['platform_money']);
        $settlement['pay_detail'] = $pay_detail;
        $settlement['order_count_detail'] = $order_count_detail;
        $settlement['order_pay_price'] = $tj['order_pay_price'];
        $settlement['total_money'] = $tj['total_money'];
        return $this->success($settlement);
    }
    public function detailOrderList(){
        $settlement_id = $this->request->param('settlement_id/d',0);
        $type = $this->request->param('type/d',1);//1买单2产品3套餐
        if($type==1){
            $b_order_ids = settleOrderModel::where(['shop_id'=>$this->request->shopId,'settle_id'=>$settlement_id])->where('b_order_id','>',0)->column('b_order_id');
            $where['shop_id'] = $this->request->shopId;
            $where['b_order_ids'] = $b_order_ids;
            $where['is_settle'] = 1;
            $order=['bo.add_time'=>'desc'];
            $model = new BuyOrderModel();
            $return = $model->list($where,$order,$this->request->page,$this->request->limit);
        }else{
            $o_ids = settleOrderModel::where(['shop_id'=>$this->request->shopId,'settle_id'=>$settlement_id])->where('order_id','>',0)->column('order_id');
            $order_ids = GoodsOrderItemModel::where(['shop_id'=>$this->request->shopId,'type'=>$type])->whereIn('order_id',$o_ids)->column('order_id');
            if(empty($order_ids)){
                $return = [
                    'count'=>0,
                    'list'=>[]
                ];
            }else{
                $where['order_ids'] = $order_ids;
                $where['is_settle'] = 1;
                $order = ['o.add_time'=>'desc'];
                $model = new GoodsOrderModel();
                $return = $model->list($where,$order,$this->request->page,$this->request->limit);
            }
        }


        return $this->success($return);
    }
    /*结算明细订单列表*/
    public function detailOrderListOld(){
        $settlement_id = $this->request->param('settlement_id/d',0);
        $type = $this->request->param('type/d',1);//1买单2产品3套餐
        if(!in_array($type,[1,2,3])) return $this->error('类型有误');
        if(null === $settlement = SettlementModel::where(['shop_id'=>$this->request->shopId,'settlement_id'=>$settlement_id,'is_delete'=>0])->find()){
            return $this->error('结算不存在');
        }
        $start_time = strtotime($settlement->settlement_time);
        $end_time = $start_time + 86400;

        $where['shop_id'] = $this->request->shopId;
        $where['start_time'] = $start_time;
        $where['end_time'] = $end_time;
        $where['is_paid'] = 1;
        $where['is_settle'] = 1;
        if(in_array($type,[2,3])){
            $order = ['o.add_time'=>'desc'];
            $order_ids = GoodsOrderItemModel::where(['shop_id'=>$this->request->shopId,'type'=>$type])->whereBetween('add_time',[$start_time,$end_time])->column('order_id');
            if(empty($order_ids)){
                $return = [
                    'count'=>0,
                    'list'=>[]
                ];
            }else{
                $where['order_ids'] = $order_ids;
                $model = new GoodsOrderModel();
                $return = $model->list($where,$order,$this->request->page,$this->request->limit);
            }
        }else{
            $order=['bo.add_time'=>'desc'];
            $model = new BuyOrderModel();
            $return = $model->list($where,$order,$this->request->page,$this->request->limit);
        }

        return $this->success($return);
    }
    /*结算明细列表*/
    public function detailList(){
        $settlement_id = $this->request->param('settlement_id/d',0);
        $type = $this->request->param('type/d',1);//1买单2产品3套餐
        if(null === $settlement = SettlementModel::where(['shop_id'=>$this->request->shopId,'settlement_id'=>$settlement_id,'is_delete'=>0])->find()){
            return $this->error('结算不存在');
        }

        $start_time = strtotime($settlement->settlement_time);
        $end_time = $start_time+86399;
        $where = [

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

            ['is_paid','=',1],

            ['add_time','between',"$start_time,$end_time"]
        ];
        //买单
        if($type==1){
            $return = [];
            return $this->success($return);
        }
        //产品
        if($type==2){
            //包含产品的订单id
            $pc_order_ids = $this->orderIds(['ot.shop_id'=>$this->request->shopId,'g.type'=>2],$start_time,$end_time);
        }
        //套餐
        if($type==3){
            //包含产品的订单id
            $pc_order_ids = $this->orderIds(['ot.shop_id'=>$this->request->shopId,'g.type'=>3],$start_time,$end_time);
        }
        //买单
        $goods_order_model = new GoodsOrderModel();
        $goods_order_model = $goods_order_model::with(['member','partner','coupon','partnerCommission'])
            ->whereBetweenTime('add_time',$start_time,$end_time)
            ->whereIn('order_id',$pc_order_ids);

        $order = ['add_time'=>'desc'];

        $field = "*";

        $append = [];

        $return = DataLogic::getDataList($goods_order_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        $list = $return['list'];
        foreach ($list as &$v){
            $commission = 0;
            foreach ($v['partnerCommission'] as $key=>$value){

                $commission += $value['commission'];
            }
            unset($v['partnerCommission']);
            //股东提成
            $v['percentage'] = sprintf("%.2f",$commission);
            //商家实收
            $v['boss_real_receive'] = sprintf("%.2f",$v['need_pay'] - $v['freight'] - $commission - $v['coupon_money']);

            $partner_role_name = '未知';
            if($v['partner']){
                if($v['partner']['role_id']==1){
                    $partner_role_name = '股东';
                }
                if($v['partner']['role_id']==2){
                    $partner_role_name = '员工';
                }
                if($v['partner']['role_id']==3){
                    $partner_role_name = '会员';
                }
                if($v['partner']['role_id']==4){
                    $partner_role_name = '自定义';
                }
                if($v['partner']['role_id']==5){
                    $partner_role_name = '投资合伙人';
                }
                if($v['partner']['role_id']==6){
                    $partner_role_name = '储值合伙人';
                }
            }
            $v['partner_role_name'] = $partner_role_name;
            $v['level'] = LevelModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'level_id'=>$v['member']['level_id']])->value('name');
            $v['nick_name'] = $v['member']['nick_name'];
            $v['mobile'] = $v['member']['mobile'];
            $v['face'] = $v['member']['face'];
            $order_goods_info = $this->orderGoodsInfos(['shop_id'=>$this->request->shopId,'order_id'=>$v['order_id']]);
            $v['goods_name'] = $order_goods_info['goods_name'];
            $v['goods_num'] = $order_goods_info['goods_num'];
            $v['goods_original_price'] = $order_goods_info['goods_original_price'];
            $v['goods_price'] = $order_goods_info['goods_price'];
            $v['type'] = '产品';
            $v['coupon_name'] = $v['coupon']?$v['coupon']['name']:null;
            unset($v['member']);
            unset($v['partner']);
            unset($v['coupon']);
        }
        $return['list'] = $list;
        return $this->success($return);
    }
    /*获取子订单产品*/
    public function orderGoodsInfos($where){
        $goods_name = '';
        $goods_num = 0;
        $goods_original_price = $goods_price = 0;
        $order_item = GoodsOrderItemModel::with(['goods'])->where($where)->select()->toArray();
        foreach ($order_item as $k=>$v){
            if($v['goods']){
                $goods_name .=$v['goods']['name'].'、';
            }
            $goods_num += $v['goods_num'];
            $goods_original_price += $v['goods_original_price'];
            $goods_price += $v['goods_price'];
            $discount[]=[
                'vip_discount_type'=>$v['vip_discount_type'],
                'discount_detail'=>$v['discount_detail'],
            ];
        }
        $return = [
            'goods_name'=>rtrim($goods_name,'、'),
            'goods_num'=>$goods_num,
            'goods_original_price'=>$goods_original_price,
            'goods_price'=>$goods_price
        ];
        return $return;
    }
    /*获取订单id*/
    public function orderIds($where,$start_time,$end_time){
        //包含产品的订单id
        $order_item = GoodsOrderItemModel::alias('ot')
            ->leftJoin('beautiful_goods g','ot.goods_id=g.goods_id')
            ->field('ot.*')
            ->where($where)
            ->whereBetween('ot.add_time',"$start_time,$end_time")
            ->select()->toArray();
        if(empty($order_item)){
            return [];
        }
        $order_ids = array_column($order_item, 'order_id');
        return $order_ids;
    }
    public function cs(){
        $c_id = '四川';
        $where[] = ['receiving_address_province','find in set',$c_id];
        $order = \app\stores\model\order\GoodsOrderModel::where($where)->select()->toArray();
        var_dump($order);
        exit;
        $set_meal_order_ids = GoodsOrderItemModel::where(['type'=>3])->column('order_id');
        $order_list = \app\stores\model\order\GoodsOrderModel::whereIn('order_id',$set_meal_order_ids)->where(['is_delete'=>0,'is_paid'=>1,'status'=>10])->select()->toArray();
        $up['status']='13';
        $update_order_ids=[];
        $order = GoodsOrderModel::where('1=1')->find();
        foreach ($order_list as $k=>$v){
            $item = GoodsOrderItemModel::where(['order_id'=>$v['order_id']])->find();
            if($v['order_type']=='pin_tuan'){
                $where_g = [
                    ['is_delete','=',0],
                    ['pin_tuan_order_id','=',$v['pin_tuan_order_id']]
                ];

            }else{
                $where_g = [
                    ['is_delete','=',0],
                    ['order_id','=',$v['order_id']],
                    ['order_item_id','=',$item->order_item_id]
                ];
            }
            $goods = OrderGoodsModel::where($where_g)->json(['use_limit_detail'],true)->find();
            //到期时间
            $order->pay_time = strtotime($v['pay_time']);
            $return = goodsEndTime($goods,$order);
            if($return['is_effect']<1){
                $update_order_ids[]=$v['order_id'];
                //GoodsOrderModel::update($up,['order_id'=>$v['order_id']]);
            }
        }
        var_dump($update_order_ids);exit;
    }
    /*锁客分佣*/
    public function LockMemberList(){
        $limit=$this->request->limit;
        $page=$this->request->page;
        $start_time = $this->request->param('start_time');
        $end_time = $this->request->param('end_time');
        $order_type = $this->request->param('order_type');
        if($order_type!==''){
            switch ($order_type){
                case 0:
                    $start_time = date("Y-m-d H:i:s",strtotime("today"));
                    $end_time = date("Y-m-d H:i:s",strtotime("today")+86399);
                    break;
                case 1:
                    $start_time = date('Y-m-d',mktime(0,0,0,date('m'),date('d')-1,date('Y')));
                    $end_time = date("Y-m-d H:i:s",strtotime("today")-1);
                    break;
                case 2:
                    $start_time = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")));
                    $end_time = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")));
                    break;
                case 3:
                    $start_time = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1-7,date("Y")));
                    $end_time = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7-7,date("Y")));
                    break;
                case 4:
                    $start_time = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),1,date("Y")));
                    $end_time = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("t"),date("Y")));
                    break;
            }
        }
        $where=[];
        $shop_id=$this->request->shopId;
        $order['a.shop_balance_logs_id']='desc';
        $where['start_time']=$start_time;
        $where['end_time']=$end_time;
        $where['balance_type']=1;
        $where['shop_id']=$shop_id;
        $res_data=ShopBalanceLogsModel::list($where,$order,$page,$limit);
        $AccountBalanceModel=new AccountBalanceModel();
        $account_info=$AccountBalanceModel->where(['shop_id'=>$shop_id,'is_delete'=>0])->find();
        $res_data['lock_money']=$account_info['lock_money'];
        $no_received_money=ShopBalanceLogsModel::where(['shop_id'=>$shop_id,'balance_type'=>1,'status'=>0])->sum('balance');
        $res_data['no_received_money']=$no_received_money;
        return $this->success($res_data);
    }


}